package com.laikan.reader.bookstart.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.RelativeLayout;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.laikan.library.components.activitys.BasicActivity;
import com.laikan.library.httpvolley.engine.HttpApiRequestEngine;
import com.laikan.library.httpvolley.engine.Requester;
import com.laikan.library.httpvolley.helper.RequestListener;
import com.laikan.library.httpvolley.helper.VolleyErrorHandler;
import com.laikan.library.httpvolley.response.HttpResponse;
import com.laikan.library.permission.CheckPermission;
import com.laikan.library.permission.PermissionActivity;
import com.laikan.library.utils.SPUtil;
import com.laikan.reader.R;
import com.laikan.reader.apirequester.UpdateUtil;
import com.laikan.reader.comment.APIProtocol;
import com.laikan.reader.comment.Constants;
import com.laikan.reader.core.HomeOptions;
import com.laikan.reader.core.LaikanApplication;
import com.laikan.reader.core.bean.BaseDataBean;
import com.laikan.reader.core.bean.VersionDetialInfo;
import com.laikan.reader.core.utils.BookFileUtils;
import com.laikan.reader.core.utils.PublicUtil;
import com.laikan.reader.database.Book;
import com.socks.library.KLog;
import com.umeng.analytics.MobclickAgent;

import java.io.File;
import java.lang.reflect.Type;
import java.net.URLDecoder;
import java.util.ArrayList;

/**
 * 欢迎页
 *
 * @author anrun
 */
public class SplashActivity extends BasicActivity {

    private static final int LOGIN_F = 1;
    protected ArrayList<Book> mData;
    private RelativeLayout rl_splash;
    private RelativeLayout rl_font;

    private static final int REQUEST_CODE = 0;//请求码

    private CheckPermission checkPermission;//检测权限器

    //配置需要取的权限
    static final String[] PERMISSION = new String[]{
        Manifest.permission.WRITE_EXTERNAL_STORAGE,// 写入权限
        Manifest.permission.READ_EXTERNAL_STORAGE,  //读取权限
        Manifest.permission.READ_PHONE_STATE,  //读取权限
    };

    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case LOGIN_F:
                    normalHomePage();
                    break;
                default:
                    break;
            }
        }

        /**
         * 普通包首页
         */
        private void normalHomePage() {

            //先判断本地有没有广告图片
            String filePath = BookFileUtils.POSTERIMGFILEPATH + "/lk_poster_bg.png";
            File file = PublicUtil.getRootPath();
            file = new File(file.getPath() + filePath);
            KLog.e("广告本地图片是否存在 :"+file.exists());
            if (file.exists()) {
                Intent intent = new Intent(SplashActivity.this, PosterActivity.class);
                startActivity(intent);
                finish();

            }else if (!SPUtil.getString("token", "").equals("")) {
                Intent intent = new Intent(mContext, HomeActivity.class);
                intent.putExtra("login_type", "login_custom");
                startActivity(intent);
                finish();
            }else {
                startActivity(new Intent(mContext, GuideActivity.class));
                finish();
            }
        }

    };

    public void onResume() {
        super.onResume();
        Intent intent = getIntent() ;
        Uri uri = intent.getData();

        if (Intent.ACTION_VIEW.equals(intent.getAction())) {
            if(uri!=null){
                if(Constants.bookFoucsPath.equals(uri.toString())){
                    LaikanApplication.setHomeOptions(HomeOptions.bookfocus);
                }
            }
        }
        MobclickAgent.onResume(this);
        //1.5秒后跳转进入主页
        checkPermission = new CheckPermission(this);
        if (Build.VERSION.SDK_INT > 22 && checkPermission.permissionSet(PERMISSION)) {
            startPermissionActivity();
        }else {
            setContentView(R.layout.lk_splash02);
//            checkSplashBg();
            mHandler.sendEmptyMessageDelayed(LOGIN_F, 1500);
        }
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void assignViews() {

    }

    //进入权限设置页面
    private void startPermissionActivity() {
        PermissionActivity.startActivityForResult(this, REQUEST_CODE, PERMISSION);
    }

    //返回结果回调
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //拒绝时，没有获取到主要权限，无法运行，关闭页面
        if (requestCode == REQUEST_CODE && resultCode == PermissionActivity.PERMISSION_DENIEG) {
            finish();
        }
    }

    /**
     * 普通包执行代码
     */
    private void checkSplashBg() {
        String filePath = BookFileUtils.SPLASHIMGFILEPATH + "/lk_splash_bg.png";
        File file = PublicUtil.getRootPath();
        file = new File(file.getPath() + filePath);

        if (file.exists()) {
            // 有新启动页图片
            rl_splash = (RelativeLayout)findViewById(R.id.rl_splash);
            rl_font = (RelativeLayout)findViewById(R.id.rl_font);
            rl_font.setVisibility(View.GONE);
            rl_splash.setBackgroundDrawable(new BitmapDrawable(BitmapFactory.decodeFile(file.getPath())));
        }
    }

    @Override
    protected void initData() {


        getPosterData();
    }

    @Override
    public void onBackPressed() {
        this.finish();
        super.onBackPressed();
    }

    @Override
    protected void setListener() {
    }

    /**
     * 访问广告页数据
     */
    private void getPosterData() {
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() {
                KLog.e("---------volley onPreExecute!!!");
            }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                BaseDataBean<VersionDetialInfo> result;
                Gson gson = new Gson();
                Type type = new TypeToken<BaseDataBean<VersionDetialInfo>>() {
                }.getType();
                try {
                    result = gson.fromJson(httpResponse.responseContent, type);
                    if (result != null && Constants.RESULT_OK.equals(result.getResult())) {
                        VersionDetialInfo detailInfo = result.getData();
                        //判断有没有广告图片url 有就进行下载
                        if(!TextUtils.isEmpty(detailInfo.getAdvertiseValue())){

                            SPUtil.putString("poster_advertise_url", detailInfo.getAdvertiseValue()); //保存广告链接
                            String title = detailInfo.getAdvertiseValue().substring(detailInfo.getAdvertiseValue().indexOf("=")+1);
                            try {
                                title = URLDecoder.decode(title, "utf-8");
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            SPUtil.putString("poster_advertise_title", title); //保存广告标题
                        }
                        UpdateUtil.downLoadPosterImg(detailInfo.getAdvertiseImg(), mContext,"isPosterImg");
                    }else {
                        KLog.e(result.getError_msg());
                    }
                }catch (JsonSyntaxException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                KLog.e("网络不给力，请重试。poster");
            }

            @Override
            public void onFinish() {

            }
        };

        Requester requester = new Requester();
        requester.setUrl(APIProtocol.laikan_check_version);
        HttpApiRequestEngine.getInstance().httpGetRequest(requester, requestListener);
    }
}